package au.chao.socket.reader;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import org.apache.log4j.Logger;

import au.chao.util.SocketUtil;

public class SocketMessageReader implements SocketReader {
	Logger log = Logger.getLogger(SocketMessageReader.class);
	Socket socket = null;

	public SocketMessageReader(Socket socket) {
		this.socket = socket;
	}

	@Override
	public Object readSocket() throws IOException {
		Object result = null;
		ObjectInputStream objInStream = null;
		try {
			objInStream = new ObjectInputStream(socket.getInputStream());
			result = objInStream.readObject();
			if (log.isDebugEnabled()) {
				log.debug("received message" + result);
			}
		} catch (ClassNotFoundException e) {
			log.error("Read Message from socket failed", e);
		} finally {
			if (objInStream != null) {
				SocketUtil.closeSocket(socket);
				SocketUtil.closeIOStream(objInStream);
			}
		}
		return result;
	}

	@Override
	public void closeSocket() throws IOException {
		SocketUtil.closeSocket(socket);
	}

}
